package com.sunthy.mall.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class FileUploadUtils {

    public static Map<String, Object> parseRequest(HttpServletRequest request){
        //工厂可以用来生产对应的物件，利用factory可以实例化接下来文件上传的处理器
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //factory首先先设置一个缓存仓库，当文件很大时，采用边缓存边处理的方式
        File repository = (File) request.getServletContext().getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);
        Map<String, Object> params = new HashMap<String,Object>();
        //利用factory生产出来一个文件处理器
        ServletFileUpload upload = new ServletFileUpload(factory);
        //  1024 bytes
//        upload.setFileSizeMax(1024);
        //利用处理器处理我们的请求：将页面提交过来的input封装成一个FileItem对象
        //页面里面每出现一个input框，那么这里面就对应一个FileItem
        try {
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem item : items) {
                //后续的处理中，表单数据和上传的文件要区别对待
                if(item.isFormField()){
                    //判断当前item是否是表单数据
                    processFormField(item, params);
                }else {
                    processUploadFile(item, params, request);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        return params;
    }

    /**
     * 处理上传的文件逻辑
     * @param item
     * @param map
     * @param request
     */
    private static void processUploadFile(FileItem item, Map<String, Object> map, HttpServletRequest request) {
        //想了解一下文件的文件名
        String fieldName = item.getFieldName();
        String fileName = item.getName();
        //对文件名进行处理
        String uuid = UUID.randomUUID().toString();
        //文件后缀名
        fileName = uuid + "-" + fileName;
        int hashCode = fileName.hashCode();
        String hexString = Integer.toHexString(hashCode);
        char[] chars = hexString.toCharArray();
        String basePath = "/image";
        for (char aChar : chars) {
            basePath = basePath + "/" + aChar;
        }
        String contentType = item.getContentType();
        boolean isInMemory = item.isInMemory();
        long sizeInBytes = item.getSize();
        System.out.println(fieldName + "-" + fileName + "-" + contentType + "-" + isInMemory + "-" + sizeInBytes);
        //将文件保存到硬盘上面
        //想把它保存在应用根目录下
        ServletContext servletContext = request.getServletContext();
        String relativePath = basePath + "/" + fileName;
        String realPath = servletContext.getRealPath(relativePath);
        File file = new File(realPath);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        try {
            item.write(file);
            map.put(fieldName, relativePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 处理常规form表单的逻辑
     * 常规form表单数据，其实只需要获取键值对就可以了
     * @param item
     * @param map
     */
    private static void processFormField(FileItem item, Map<String, Object> map) {
        String key = item.getFieldName();
        String value = null;
        try {
            value = item.getString("utf-8");
            //判断是username-
            map.put(key, value);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(key + ":" + value);
    }
}
